/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.demo.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpHost;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.download.DownloadManager;
import com.mol.market.common.download.DownloadService;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.network.HttpClientFactory;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.network.ResponseCacheManager;
import com.mol.market.common.util.AlarmManageUtils;
import com.mol.market.common.util.CacheManager;
import com.mol.market.common.util.DialogUtil;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.UpdateInfo;
import com.mol.market.demo.widget.BaseFragmentActivity;
import com.mol.market.ui.PersonalAccountFragment;
import com.mol.market.ui.SplashActivity;
import com.mol.market.ui_v4.PagerAdapter;
import com.mol.market.widget.SlotMachinesWidget;

/**
 * @author Chaos	
 * @Description 新的首页
 * @date 2012-12-10 
 */
public final class HomeFragmentActivity extends BaseFragmentActivity
        implements ApiAsyncTask.ApiRequestListener{
    private static final int DIALOG_EXIT = 1;
    private static final int DIALOG_OPT_UPDATE = 2;
    private static final int DIALOG_FORCE_UPDATE = 3;

	public static final int TAB_GAME = 0;
	public static final int TAB_TYPE = 1;
	
    private boolean isCheckedUpdate;
    private PagerAdapter adapter;
    
    // Game页的配置信息
	private int mGameTabPos = TAB_GAME;

	public int getGameTabPos() {
		return mGameTabPos;
	}
	
	public void setGameTabPos(int gameTabPos) {
		this.mGameTabPos = gameTabPos;
		this.adapter.notifyDataSetChanged();
	}
	
    // 检查用户是否切换CMWAP网络
    private BroadcastReceiver mNetworkReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            HttpHost proxy = Utils.detectProxy(getApplicationContext());
            if (proxy != null) {
                HttpClientFactory.get().getHttpClient().useProxyConnection(proxy);
            } else {
                HttpClientFactory.get().getHttpClient().useDefaultConnection();
            }
        }
    };

    // 检查机锋市场版本更新
    private BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constants.BROADCAST_FORCE_EXIT)) {
                // 强制退出机锋市场
                exit();
            } else if (action.equals(Constants.BROADCAST_REMIND_LATTER)) {
                // do nothing
            } else if (action.equals(Constants.BROADCAST_DOWNLOAD_OPT)) {
                // start download
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mSession
                        .getUpdateUri()));
                request.setPackageName(mSession.getPackageName());
                request.setTitle(Constants.UPDATE_FILE_NAME);
                request.setShowRunningNotification(true);
                request.setSourceType(com.mol.market.common.download.Constants.DOWNLOAD_FROM_OTA);
                request.setMimeType(com.mol.market.common.download.Constants.MIMETYPE_APK);
                mSession.getDownloadManager().enqueue(context, request, new DownloadManager.EnqueueListener() {

                    @Override
                    public void onFinish(long id) {
                        mSession.setUpdateID(id);
                    }
                });
                mSession.mIsDownloadOta = true;

            } else if (action.equals(Constants.BROADCAST_DOWNLOAD)) {
                // start download
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(mSession
                        .getUpdateUri()));
                request.setPackageName(mSession.getPackageName());
                request.setTitle(Constants.UPDATE_FILE_NAME);
                request.setShowRunningNotification(true);
                request.setSourceType(com.mol.market.common.download.Constants.DOWNLOAD_FROM_OTA);
                request.setMimeType(com.mol.market.common.download.Constants.MIMETYPE_APK);
                mSession.getDownloadManager().enqueue(context, request, new DownloadManager.EnqueueListener() {

                    @Override
                    public void onFinish(long id) {
                        mSession.setUpdateID(id);
                    }
                });
                mSession.mIsDownloadOta = true;
                HomeFragmentActivity.this.finish();
            }
        }
    };
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        registerReceivers();

        // send product update broadcast
        if (Utils.isNeedCheckUpgrade(getApplicationContext())) {
            mSession.setUpdataCheckTime(System.currentTimeMillis());
            MarketAPI.submitAllInstalledApps(getApplicationContext());
        }

        // 网络正常，开始检查版本更新
        if (!mSession.mIsInApp) {
            checkNewSplash();
            MarketAPI.checkUpdate(getApplicationContext(), this);
            MarketAPI.checkUpgrade(getApplicationContext(), this);
			if (mSession.isLogin() && !TextUtils.isEmpty(mSession.getInstallPkg())) {
				MarketAPI.insertHistoryInstall(getApplicationContext(), this,
						mSession.getInstallPkg());
			}
            initDataForWidget();
            mSession.mIsInApp = true;
        }

        if (mSession.isFirstLogin()) {
            mSession.setFirstLogin(false);
            AlarmManageUtils.notifyPushService(getApplicationContext(), false);
            createDesktopIcon();
        }

        setContentView(R.layout.demo_activity_home);
        initTabs();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
    }

    private void unregisterReceiver() {
        unregisterReceiver(mNetworkReceiver);
        unregisterReceiver(mUpdateReceiver);
    }

    /** 创建对话框，询问是否创建桌面图标 */
    private void createDesktopIcon(){
        DialogUtil.createYesNoDialog(this, 0x12,
                getString(R.string.dialog_createDesktopIcon),
                new DialogUtil.YesNoDialogListener() {

                    @Override
                    public void onYesDialog(int id) {
                        Utils.createDesktopIcon(
                                HomeFragmentActivity.this,
                                getResources().getString(R.string.app_name),
                                R.drawable.app_icon,
                                SplashActivity.class);
                    }

                    @Override
                    public void onNoDialog(int id) {
                        //do nothing
                        return;
                    }
                }).show();
    }

    /*
     * 检查是否有新的Splash
     */
    private void checkNewSplash() {
        sendBroadcast(new Intent(Constants.BROADCAST_SPLASH_CHECK_UPGRADE));
    }

    private void registerReceivers() {
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetworkReceiver, filter);

        IntentFilter updateFilter = new IntentFilter();
        updateFilter.addAction(Constants.BROADCAST_FORCE_EXIT);
        updateFilter.addAction(Constants.BROADCAST_REMIND_LATTER);
        updateFilter.addAction(Constants.BROADCAST_DOWNLOAD_OPT);
        updateFilter.addAction(Constants.BROADCAST_DOWNLOAD);
        registerReceiver(mUpdateReceiver, updateFilter);
    }
    
    
    private void initTabs(){
        ActionBar bar   = getSupportActionBar();
        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        
        ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
        
        adapter = new PagerAdapter(getSupportFragmentManager(), this, getApplicationContext(), pager, bar);
        
        setupTabs( adapter, bar);
        pager.setAdapter(adapter);
    }
    
    protected void setupTabs(PagerAdapter adapter,ActionBar bar){
        Tab tab1 = bar.newTab().setText(R.string.tab_recommend);
        Tab tab2 = bar.newTab().setText(R.string.tab_rank);
        Tab tab3 = bar.newTab().setText(R.string.tab_game);
        Tab tab4 = bar.newTab().setText(R.string.tab_account);
//        Tab tab5 = bar.newTab().setText(R.string.tab_app);

        adapter.addTab(tab1, HomeFragment.class, tab1.getText(), null);
        adapter.addTab(tab2, RankFragment.class, tab2.getText(), null);
        adapter.addTab(tab3, GameFragment.class, tab3.getText(), null);
        adapter.addTab(tab4, PersonalAccountFragment.class, tab4.getText(), null);
//        adapter.addTab(tab5, AppFragment.class, tab5.getText(), null);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        exit();
    }

    /**
     * 退出机锋市场
     */
    private void exit() {
        if (mSession != null && mSession.hasDownloadTask()) {
            moveTaskToBack(false);
        } else {
            doExit();
        }
    }

    /**
     * 退出机锋市场<br>
     * 进行必要的资源回收工作
     */
    private void doExit() {

        final Context context = getApplicationContext();
        //记录退出时间
        mSession.setUserLastLoginTime(System.currentTimeMillis());

//        if (mSession.isSecondLogin()) {
//            AlarmManageUtils.notifyCallbackService(this,
//                    AlarmManageUtils.PushRules.NOLOGIN_SILENCE_USER_7_DAY);
//        } else {
//            AlarmManageUtils.notifyCallbackService(this,
//                    AlarmManageUtils.PushRules.NOLOGIN_NEW_USER_3_DAY);
//        }

        // 清除所有API缓存
        ResponseCacheManager.getInstance().clear();
        // 清除所有图片缓存
        CacheManager cache = CacheManager.getInstance(context);
        cache.clearExpiredFile(context);
        cache.clearFromMemory(context);
        // 清除坏通知
        Intent clearIntent = new Intent(context, DownloadService.class);
        clearIntent.putExtra(DownloadService.CLEAR_BAD_NOTIFICATION, 1);
        startService(clearIntent);
        // 2010/8/25 释放连接资源
        HttpClientFactory.get().close();
        if (mSession != null) {
            // 清除所有观察者
            mSession.deleteObservers();
            // 回收Session
            mSession.close();
            mSession = null;
        }
        AlarmManageUtils.scheduleUpdateAlarm(context);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(R.drawable.notification_icon);
        finish();
    }

    @Override
    public void onSuccess(int method, Object obj) {
        if (isFinishing()) {
            return;
        }

        if (method == MarketAPI.ACTION_CHECK_NEW_VERSION) {

            handleUpdate((UpdateInfo) obj);

		} else if (method == MarketAPI.ACTION_CHECK_UPGRADE) {

			checkUpdateAppsNotification();
		} else if (method == MarketAPI.ACTION_INSERT_HISTORY_INSTALL) {
			mSession.setInstallPkg("");
		}
    }

    @Override
    public void onError(int method, int statusCode) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    /*
     * 检查机锋市场的更新
     */
    private void handleUpdate(UpdateInfo info) {

        // 2011/9/21 fix NullPointerException
        if (mSession == null || info == null) {
            return;
        }

        // update the info to local memory
        int updateLevel = info.getUpdageLevel();
        mSession.setUpdateInfo(info.getVersionName(), info.getVersionCode(), info.getDescription(),
                info.getApkUrl(), updateLevel);
        File file = new File(getFilesDir(), Constants.UPDATE_FILE_NAME + ".apk");
        if (file.exists()) {
            file.delete();
        }
        // 有可用升级
        if (Constants.FORCE_UPDATE == updateLevel) {
            showDialog(DIALOG_FORCE_UPDATE);
        } else if (Constants.SUGGEST_UPDATE == updateLevel) {
            showDialog(DIALOG_OPT_UPDATE);
        }
    }

    /**
     * 检查是否需要弹出应用更新通知
     */
    private void checkUpdateAppsNotification() {

        if (mSession.isNotificationUpdateApps() && mSession.getUpgradeNumber() > 0) {
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            Notification notification = new Notification();
            notification.defaults = Notification.DEFAULT_LIGHTS;
            notification.icon = R.drawable.notification_icon;
            notification.tickerText = getString(R.string.notification_update_info,
                    mSession.getUpgradeNumber());
            notification.when = System.currentTimeMillis();
            Intent intent = new Intent(Constants.BROADCAST_CLICK_INTENT);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0,
                    intent, PendingIntent.FLAG_CANCEL_CURRENT);
            notification.setLatestEventInfo(getApplicationContext(),
                    getString(R.string.notification_update_info_title),
                    getString(R.string.notification_update_info, mSession.getUpgradeNumber()),
                    pendingIntent);
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify(R.drawable.notification_icon, notification);
            //刷新顶部Menu Icon
            invalidateOptionsMenu();
        }
    }

    /**
     * 为Widget去请求数据
     */
    private void initDataForWidget(){
        MarketAPI.getHomeRecommend(getApplicationContext(), new ApiAsyncTask.ApiRequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void onSuccess(int method, Object obj) {
                sendToSlotMachinesWidget((ArrayList<HashMap<String, Object>>) ((HashMap<String, Object>) obj)
                        .get(Constants.KEY_PRODUCT_LIST));
            }

            @Override
            public void onError(int method, int statusCode) {
                //do nothing
            }
        }, 51, 100, true);
    }
    
    @Override
    protected Dialog onCreateDialog(final int id) {
        switch (id) {
        case DIALOG_EXIT:
            return new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle(getString(R.string.exit_gmarket))
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            // 退出机锋市场
                            exit();
                        }
                    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            try {
                                HomeFragmentActivity.this.dismissDialog(id);
                            } catch (IllegalArgumentException e) {
                            }
                        }
                    }).create();

        case DIALOG_OPT_UPDATE:

            String optVersionName = mSession.getUpdateVersionName();
            String optUpdateDesc = mSession.getUpdateVersionDesc();
            if (!TextUtils.isEmpty(optUpdateDesc)) {
                optUpdateDesc = optUpdateDesc.replace("\r", "");
            }
            return new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle(R.string.find_new_version)
                    .setMessage(getString(R.string.update_prompt, optVersionName) + optUpdateDesc)
                    .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            sendBroadcast(new Intent(Constants.BROADCAST_DOWNLOAD_OPT));
                            removeDialog(id);
                        }
                    })
                    .setNegativeButton(R.string.btn_next_time,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    sendBroadcast(new Intent(Constants.BROADCAST_REMIND_LATTER));
                                    removeDialog(id);
                                }
                            }).create();

        case DIALOG_FORCE_UPDATE:

            String forceVersionName = mSession.getUpdateVersionName();
            String forceUpdateDesc = mSession.getUpdateVersionDesc().replace("\r", "");
            return new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle(R.string.find_new_version)
                    .setMessage(
                            getString(R.string.update_prompt_stronger, forceVersionName)
                                    + forceUpdateDesc)
                    .setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            sendBroadcast(new Intent(Constants.BROADCAST_DOWNLOAD));
                            removeDialog(id);
                        }
                    }).setNegativeButton(R.string.btn_exit, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            sendBroadcast(new Intent(Constants.BROADCAST_FORCE_EXIT));
                            removeDialog(id);
                        }
                    }).setOnCancelListener(new OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            sendBroadcast(new Intent(Constants.BROADCAST_FORCE_EXIT));
                        }
					}).create();

        default:
            break;
        }
        return super.onCreateDialog(id);
    }

    /**
     * 将图片信息(url)发送给widget
     * @param list
     */
    private void sendToSlotMachinesWidget(ArrayList<HashMap<String, Object>> list){
        Intent intent = new Intent(SlotMachinesWidget.ACTION_APP);
        intent.putExtra(SlotMachinesWidget.INTENT_APP_INFO, list);
        sendBroadcast(intent);
    }
}
